package io.coderyeah.search.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.coderyeah.basic.Result;
import io.coderyeah.basic.exception.BusinessException;
import io.coderyeah.basic.service.BaiduAiAuditService;
import io.coderyeah.basic.util.*;
import io.coderyeah.order.domain.OrderPetAcquisition;
import io.coderyeah.order.mapper.OrderPetAcquisitionMapper;
import io.coderyeah.org.domain.Employee;
import io.coderyeah.org.domain.Shop;
import io.coderyeah.org.mapper.EmployeeMapper;
import io.coderyeah.org.mapper.ShopMapper;
import io.coderyeah.pet.domain.Pet;
import io.coderyeah.pet.mapper.PetMapper;
import io.coderyeah.search.domain.SearchMasterMsg;
import io.coderyeah.search.domain.SearchMasterMsgAuditLog;
import io.coderyeah.search.dto.SearchDTO;
import io.coderyeah.search.mapper.SearchMasterMsgAuditLogMapper;
import io.coderyeah.search.mapper.SearchMasterMsgMapper;
import io.coderyeah.search.service.SearchMasterMsgService;
import io.coderyeah.user.domain.LoginInfo;
import io.coderyeah.user.domain.User;
import io.coderyeah.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author coderyeah
 * @description 针对表【t_search_master_msg】的数据库操作Service实现
 * @createDate 2022-09-28 10:43:32
 */
@Service
@Slf4j
public class SearchMasterMsgServiceImpl extends ServiceImpl<SearchMasterMsgMapper, SearchMasterMsg> implements SearchMasterMsgService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private BaiduAiAuditService baiduAiAuditService;
    @Resource
    private SearchMasterMsgAuditLogMapper logMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private OrderPetAcquisitionMapper acquisitionMapper;
    @Resource
    private PetMapper petMapper;

    @Transactional// 开启事务
    @Override
    public Result publish(SearchMasterMsg searchMasterMsg, HttpServletRequest req) {
        // 参数校验
        if (StrUtil.isBlank(searchMasterMsg.getAddress()) || StrUtil.isBlank(searchMasterMsg.getName())) {
            return Result.fail("参数不能为空！！！");
        }
        // 获取当前寻主消息发布人
        LoginInfo loginInfo = LoginContext.getLoginInfo(req);
        // 找到当前loginInfo的user对象
        assert loginInfo != null;
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getLogininfoId, loginInfo.getId()));
        // 保存寻主消息
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.insert(searchMasterMsg);
        // 百度ai智能审核
        // 审核文本内容
        final Boolean bool1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle() + searchMasterMsg.getCoatColor());
        // 审核图片
        final Boolean bool2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        // 提交审核日志
        final SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
        log.setMsgId(searchMasterMsg.getId());
        if (bool1 && bool2) {
            // 发布消息审核成功 0-1
            searchMasterMsg.setState(1);
            // 查询所有店铺
            final List<Shop> shops = shopMapper.selectList(new LambdaUpdateWrapper<>());
            // 获取发布人位置的经纬度
            final Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            // 获取距离最近的店铺
            final Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if (nearestShop != null) {
//                searchMasterMsg.setState(2);
                searchMasterMsg.setShopId(nearestShop.getId());
                // 更新发布信息
                searchMasterMsgMapper.updateById(searchMasterMsg);
                // 发送短信通知店铺管理员
                // 通过shopId查找店铺管理员
                final Employee employee = employeeMapper.selectOne(new LambdaUpdateWrapper<Employee>().eq(Employee::getShopId, nearestShop.getId()));
//                SmsUtils.sendSms(employee.getPhone(), "您有新的订单啦！请前往" + searchMasterMsg.getAddress() + "完成收购！");
                System.out.println("您有新的订单啦！请前往" + searchMasterMsg.getAddress() + "完成收购！");
            } else {
                // 放入寻主池
                searchMasterMsg.setState(3);
                // 更新发布信息
                searchMasterMsgMapper.updateById(searchMasterMsg);
            }
            log.setState(1); // 审核成功
            log.setNote("AI审核通过");
            // 保存审核日志
            logMapper.insert(log);
        } else {
            // 审核失败
            log.setState(0); // 审核成功
            log.setNote("AI审核未通过");
            logMapper.insert(log);
            // 删除寻主消息
            searchMasterMsgMapper.deleteById(searchMasterMsg.getId());
//            SmsUtils.sendSms(user.getPhone(),"审核未通过,请重新编辑内容后上传！！！");
            return Result.fail("发布失败,请修改信息后再次提交");
        }
        return Result.success("发布成功");
    }

    @Override
    public Result getAllMsgByUserId(SearchDTO searchDTO, HttpServletRequest req) {
        final LoginInfo loginInfo = LoginContext.getLoginInfo(req);
        assert loginInfo != null;
        final User user = userMapper.selectOne(new LambdaUpdateWrapper<User>().eq(User::getLogininfoId, loginInfo.getId()));
        searchDTO.setUserId(Math.toIntExact(user.getId()));
        List<SearchMasterMsg> list = searchMasterMsgMapper.getByLoginInfoId(searchDTO);
        Long totals = searchMasterMsgMapper.getCounts(searchDTO);
        return Result.success(list, totals);
    }

    @Override
    public Result toHandle(SearchDTO searchDTO, HttpServletRequest req) {
        final LoginInfo loginInfo = LoginContext.getLoginInfo(req);
        assert loginInfo != null;
        Employee employee = employeeMapper.selectOne(new LambdaQueryWrapper<Employee>().eq(Employee::getLogininfoId, loginInfo.getId()));
        if (null != employee.getShopId()) {
            // 如果shopId不为空则是店铺管理员只能查寻自己店铺的消息
            searchDTO.setShopId(employee.getShopId());
        }
        // shopId为空则是平台管理员查询所有待处理消息
        searchDTO.setState(1);//状态为1表示审核成功待处理
        final List<SearchMasterMsg> list = searchMasterMsgMapper.getByLoginInfoId(searchDTO);
        Long totals = searchMasterMsgMapper.getCounts(searchDTO);
        return Result.success(list, totals);
    }

    @Override
    public Result pool(SearchDTO searchDTO, HttpServletRequest req) {
        // 寻主池
        searchDTO.setState(3);
        final List<SearchMasterMsg> list = searchMasterMsgMapper.getByLoginInfoId(searchDTO);
        Long totals = searchMasterMsgMapper.getCounts(searchDTO);
        return Result.success(list, totals);
    }

    @Override
    public Result getFinishedMsg(SearchDTO searchDTO, HttpServletRequest req) {
        searchDTO.setState(2);// 处理完成
        final List<SearchMasterMsg> list = searchMasterMsgMapper.getByLoginInfoId(searchDTO);
        Long totals = searchMasterMsgMapper.getCounts(searchDTO);
        return Result.success(list, totals);
    }

    @Override
    public Result reject(Long id) {
        // 拒单业务
        // 将寻主消息放入寻主池 shop_id置空
        final SearchMasterMsg masterMsg = searchMasterMsgMapper.selectById(id);
        masterMsg.setState(3);
        masterMsg.setShop(null);
        searchMasterMsgMapper.updateById(masterMsg);
        return Result.success(null);
    }

    @Transactional
    @Override
    public Result accept(Map<String, String> map) {
        final String msgId = map.get("msgId");
        final String empId = map.get("handler");
        final String note = map.get("note");
        // 校验当前订单是否已经在处理
        final OrderPetAcquisition order = acquisitionMapper.selectOne(new LambdaUpdateWrapper<OrderPetAcquisition>().eq(OrderPetAcquisition::getSearchMasterMsgId, msgId));
        if (null != order) {
            // 订单已经存在
            throw new BusinessException("订单正在处理，请勿重复接单...");
        }
        // 通过msgId生成宠物，录入到系统
        final SearchMasterMsg masterMsg = searchMasterMsgMapper.selectById(msgId);
        Pet pet = msg2pet(masterMsg);
        petMapper.insert(pet);
        // 生成收购订单
        OrderPetAcquisition orderPetAcquisition = buildOrderPetAcquisition(masterMsg, empId, note, pet);
        // 保存订单
        acquisitionMapper.insert(orderPetAcquisition);
        // 通过处理人去收回宠物
        final Employee employee = employeeMapper.selectById(empId);
        SmsUtils.sendSms(employee.getPhone(), "你有新的订单，请及时处理，地址：" + masterMsg.getAddress());
        System.out.println("你有新的订单，请及时处理，地址：" + masterMsg.getAddress());
        return Result.success(null);
    }

    private OrderPetAcquisition buildOrderPetAcquisition(SearchMasterMsg masterMsg, String empId, String note, Pet pet) {
        final OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrdersn(CodeGenerateUtils.generateOrderSn(Long.parseLong(empId)));
        order.setSearchMasterMsgId(masterMsg.getId());
        order.setPetId(pet.getId());
        order.setState(0);// 待处理
        order.setUserId(masterMsg.getUserId());
        order.setAddress(masterMsg.getAddress());
        order.setDigest(note);
        // 设置两天内未处理自动取消订单
        order.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));
        order.setPrice(masterMsg.getPrice());
        order.setShopId(masterMsg.getShopId());
        order.setEmpId(Long.valueOf(empId));
        return order;
    }

    private Pet msg2pet(SearchMasterMsg masterMsg) {
        final Pet pet = new Pet();
        pet.setName(masterMsg.getName());
        pet.setShopId(masterMsg.getShopId());
        pet.setUserId(masterMsg.getUserId());
        pet.setPetType(masterMsg.getType());
        pet.setCostprice(masterMsg.getPrice());
        pet.setSearchMasterMsgId(masterMsg.getId());
        return pet;
    }
}




